<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="" prop="code">
        <el-input
          v-model="queryParams.code"
          placeholder="请输入条形码"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="" prop="status">
        <el-select v-model="queryParams.status" style="width: 150px" placeholder="请选择状态" clearable>
          <el-option
            v-for="dict in service_barcode_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
<!--      <el-form-item label="参与活动" prop="activity">-->
<!--        <el-select v-model="queryParams.activity" style="width: 150px" placeholder="请选择参与活动" clearable>-->
<!--          <el-option-->
<!--            v-for="dict in service_barcode_activity_status"-->
<!--            :key="dict.value"-->
<!--            :label="dict.label"-->
<!--            :value="dict.value"-->
<!--          />-->
<!--        </el-select>-->
<!--      </el-form-item>-->
<!--&lt;!&ndash;      <el-form-item label="导入时间" prop="createTime">&ndash;&gt;-->
<!--&lt;!&ndash;        <el-date-picker&ndash;&gt;-->
<!--&lt;!&ndash;            v-model="daterangeCreated"&ndash;&gt;-->
<!--&lt;!&ndash;            value-format="YYYY-MM-DD"&ndash;&gt;-->
<!--&lt;!&ndash;            type="daterange"&ndash;&gt;-->
<!--&lt;!&ndash;            range-separator="-"&ndash;&gt;-->
<!--&lt;!&ndash;            start-placeholder="开始日期"&ndash;&gt;-->
<!--&lt;!&ndash;            end-placeholder="结束日期"&ndash;&gt;-->
<!--&lt;!&ndash;        ></el-date-picker>&ndash;&gt;-->
<!--&lt;!&ndash;      </el-form-item>&ndash;&gt;-->
<!--&lt;!&ndash;      <el-form-item label="相关联的质保卡" prop="warrantyCardId">&ndash;&gt;-->
<!--&lt;!&ndash;        <el-input&ndash;&gt;-->
<!--&lt;!&ndash;          v-model="queryParams.warrantyCardId"&ndash;&gt;-->
<!--&lt;!&ndash;          placeholder="请输入相关联的质保卡"&ndash;&gt;-->
<!--&lt;!&ndash;          clearable&ndash;&gt;-->
<!--&lt;!&ndash;          @keyup.enter="handleQuery"&ndash;&gt;-->
<!--&lt;!&ndash;        />&ndash;&gt;-->
<!--&lt;!&ndash;      </el-form-item>&ndash;&gt;-->
<!--      <el-form-item>-->
<!--       -->
<!--      </el-form-item>-->
    </el-form>

    <!--  按钮  -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['merchant:barcode:add']"
        >新增</el-button>
      </el-col>
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="success"-->
<!--          plain-->
<!--          icon="Edit"-->
<!--          :disabled="single"-->
<!--          @click="handleUpdate"-->
<!--          v-hasPermi="['merchant:barcode:edit']"-->
<!--        >修改</el-button>-->
<!--      </el-col>-->
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="danger"-->
<!--          plain-->
<!--          icon="Delete"-->
<!--          :disabled="multiple"-->
<!--          @click="handleDelete"-->
<!--          v-hasPermi="['merchant:barcode:remove']"-->
<!--        >删除</el-button>-->
<!--      </el-col>-->
      <el-col :span="1.5">
        <el-button
            type="info"
            plain
            icon="Upload"
            @click="handleImport"
            v-hasPermi="['merchant:barcode:import']"
        >导入</el-button>
      </el-col>
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="warning"-->
<!--          plain-->
<!--          icon="Download"-->
<!--          @click="handleExport"-->
<!--          v-hasPermi="['merchant:barcode:export']"-->
<!--        >导出</el-button>-->
<!--      </el-col>-->
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table height="calc(100vh - 250px)" stripe="true" v-loading="loading" :data="barcodeList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
<!--      <el-table-column label="Id" align="center" prop="Id" />-->
      <el-table-column label="出库日期" align="center" prop="deliveryDate" />
      <el-table-column label="成品代号" align="center" prop="productCode" />
      <el-table-column label="SIZE名" align="center" prop="productName" width="310" />
      <el-table-column label="出库数量" align="center" prop="deliveryQuantity" />
      <el-table-column label="条形码" align="center" prop="code" />
      <el-table-column label="生产日期" align="center" prop="productionDate" />
      <el-table-column label="目的地" align="center" prop="destination" />
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="service_barcode_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="参加活动" align="center" prop="activity">
        <template #default="scope">
          <dict-tag :options="service_barcode_activity_status" :value="scope.row.activity"/>
        </template>
      </el-table-column>
      <el-table-column label="导入时间" align="center" prop="createTime" width="180">
        <template #default="scope">
          <span>{{ scope.row.createTime }}</span>
        </template>
      </el-table-column>
      <el-table-column label="更新时间" align="center" prop="updateTime" width="180">
        <template #default="scope">
          <span>{{ scope.row.updateTime }}</span>
        </template>
      </el-table-column>
<!--      <el-table-column label="相关联的质保卡" align="center" prop="warrantyCardId" />-->
<!--      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">-->
<!--        <template #default="scope">-->
<!--          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['merchant:barcode:edit']">修改</el-button>-->
<!--          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['merchant:barcode:remove']">删除</el-button>-->
<!--        </template>-->
<!--      </el-table-column>-->
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改条形码对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="barcodeRef" :model="form2" :rules="rules" label-width="80px">
        <el-form-item label="出库日" prop="deliveryDate">
          <el-input v-model="form2.deliveryDate" placeholder="请输入出库日" />
        </el-form-item>
        <el-form-item label="成品代号" prop="productCode">
          <el-input v-model="form2.productCode" placeholder="请输入成品代号" />
        </el-form-item>
        <el-form-item label="SIZE名" prop="productName">
          <el-input v-model="form2.productName" placeholder="请输入SIZE名" />
        </el-form-item>
        <el-form-item label="出库数量" prop="deliveryQuantity">
          <el-input v-model="form2.deliveryQuantity" type="number" placeholder="请输入出库数量" />
        </el-form-item>
        <el-form-item label="条形码" prop="code">
          <el-input v-model="form2.code" placeholder="请输入条形码" />
        </el-form-item>
        <el-form-item label="生产日期" prop="productionDate">
          <el-input v-model="form2.productionDate" placeholder="请输入生产日期" />
        </el-form-item>
        <el-form-item label="目的地" prop="destination">
          <el-input v-model="form2.destination" placeholder="请输入目的地" />
        </el-form-item>
        <el-form-item label="数据状态">
          <el-radio-group v-model="form2.dataStatus">
            <el-radio :value="1">新增</el-radio>
            <el-radio :value="2">更新</el-radio>
          </el-radio-group>
        </el-form-item>
<!--        <el-form-item label="状态" prop="status">-->
<!--          <el-radio-group v-model="form.status">-->
<!--            <el-radio-->
<!--              v-for="dict in service_barcode_status"-->
<!--              :key="dict.value"-->
<!--              :label="parseInt(dict.value)"-->
<!--            >{{dict.label}}</el-radio>-->
<!--          </el-radio-group>-->
<!--        </el-form-item>-->
<!--        <el-form-item label="参加互动" prop="activity">-->
<!--          <el-radio-group v-model="form.activity">-->
<!--            <el-radio-->
<!--              v-for="dict in service_barcode_activity_status"-->
<!--              :key="dict.value"-->
<!--              :label="parseInt(dict.value)"-->
<!--            >{{dict.label}}</el-radio>-->
<!--          </el-radio-group>-->
<!--        </el-form-item>-->
<!--        <el-form-item label="相关联的质保卡" prop="warrantyCardId">-->
<!--          <el-input v-model="form.warrantyCardId" placeholder="请输入相关联的质保卡" />-->
<!--        </el-form-item>-->
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 导入  -->
    <el-dialog :title="upload.title" v-model="upload.open" width="400px" append-to-body>
      <el-upload
          ref="uploadRef"
          :limit="1"
          accept=".xlsx, .xls"
          :headers="upload.headers"
          :action="upload.url + '?updateSupport=' + upload.updateSupport"
          :disabled="upload.isUploading"
          :on-progress="handleFileUploadProgress"
          :on-success="handleFileSuccess"
          :auto-upload="false"
          drag
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="el-upload__tip text-center">
            <div class="el-upload__tip">
              <el-checkbox v-model="upload.updateSupport" />是否更新已经存在的条形码数据
            </div>
            <span>仅允许导入xls、xlsx格式文件。</span>
            <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link>
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFileForm">确 定</el-button>
          <el-button @click="upload.open = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Barcode">
import { listBarcode, getBarcode, delBarcode, addBarcode, updateBarcode } from "@/api/merchant/barcode";
import {getToken} from "@/utils/auth";

const { proxy } = getCurrentInstance();
const { service_barcode_status, service_barcode_activity_status } = proxy.useDict('service_barcode_status', 'service_barcode_activity_status');

const barcodeList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const daterangeCreated = ref([]);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    code: null,
    status: null,
    activity: null,
    createTime: null,
    warrantyCardId: null
  },
  rules: {
    code: [{ required: true, message: "条形码不能为空", trigger: "blur" }],
  }
});

const { queryParams, form, rules } = toRefs(data);

const form2 = reactive({
  deliveryDate: null,
  productCode: null,
  productName: null,
  deliveryQuantity: null,
  productionDate: null,
  destination: null,
  dataStatus: 1,
})

const upload = reactive({
  // 是否显示弹出层（条形码导入）
  open: false,
  // 弹出层标题（条形码导入）
  title: "",
  // 是否禁用上传
  isUploading: false,
  // 是否更新已经存在的条形码
  updateSupport: 0,
  // 设置上传的请求头部
  headers: { Authorization: "Bearer " + getToken() },
  // 上传的地址
  url: import.meta.env.VITE_APP_BASE_API + "/merchant/barcode/importData"
});

/** 查询条形码列表 */
function getList() {
  loading.value = true;
  queryParams.value.params = {};
  if (null != daterangeCreated && '' != daterangeCreated) {
    queryParams.value.params["beginCreated"] = daterangeCreated.value[0];
    queryParams.value.params["endCreated"] = daterangeCreated.value[1];
  }
  listBarcode(queryParams.value).then(response => {
    barcodeList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    Id: null,
    code: null,
    status: null,
    activity: null,
    createTime: null,
    warrantyCardId: null,

    deliveryDate: null,
    productCode: null,
    productName: null,
    deliveryQuantity: null,
    productionDate: null,
    destination: null,
    dataStatus: 1,
  };
  proxy.resetForm("barcodeRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  daterangeCreated.value = [];
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.Id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加条形码";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _Id = row.Id || ids.value
  getBarcode(_Id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改条形码";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["barcodeRef"].validate(valid => {
    // if (valid) {
    //   if (form.value.Id != null) {
    //     updateBarcode(form.value).then(response => {
    //       proxy.$modal.msgSuccess("修改成功");
    //       open.value = false;
    //       getList();
    //     });
    //   } else {
    //     addBarcode(form.value).then(response => {
    //       proxy.$modal.msgSuccess("新增成功");
    //       open.value = false;
    //       getList();
    //     });
    //   }
    // }

    if (form2.dataStatus == 1) {
      addBarcode(form2).then(response => {
        if (response.code == 200) {
          proxy.$modal.msgSuccess(response.msg);
          open.value = false;
          getList();
        } else {
          proxy.$modal.msgError(response.msg);
        }
      });
    } else {
      updateBarcode(form2).then(response => {
        if (response.code == 200) {
          proxy.$modal.msgSuccess(response.msg);
          open.value = false;
          getList();
        } else {
          proxy.$modal.msgError(response.msg);
        }
      });
    }

    form2.dataStatus = 1;
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _Ids = row.Id || ids.value;
  proxy.$modal.confirm('是否确认删除条形码编号为"' + _Ids + '"的数据项？').then(function() {
    return delBarcode(_Ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导入按钮操作 */
function handleImport() {
  upload.title = "条形码导入";
  upload.open = true;
};

/** 下载模板操作 */
function importTemplate() {
  proxy.download("merchant/barcode/importTemplate", {
  }, `barcode_template_${new Date().getTime()}.xlsx`);
};

/**文件上传中处理 */
const handleFileUploadProgress = (event, file, fileList) => {
  upload.isUploading = true;
};

/** 文件上传成功处理 */
const handleFileSuccess = (response, file, fileList) => {
  upload.open = false;
  upload.isUploading = false;
  proxy.$refs["uploadRef"].handleRemove(file);
  proxy.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
  getList();
};

/** 提交上传文件 */
function submitFileForm() {
  proxy.$refs["uploadRef"].submit();
};


/** 导出按钮操作 */
function handleExport() {
  proxy.download('merchant/barcode/export', {
    ...queryParams.value
  }, `barcode_${new Date().getTime()}.xlsx`)
}

function formmatter (row, column) {
  if (row.activity === 1) {
    return '参加'
  } else {
    return '不参加'
  }
}

getList();
</script>
<style lang="scss" scoped>
.el-form-item {
  //margin-bottom: 15px !important;
}

.el-form--inline .el-form-item {
  margin-right: 0px;
}
//.el-form-item {
//  width: 192px;
//}
.el-input{
  margin-right: 10px;
}
</style>